package com.edou.member.interceptor;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.edou.base.constant.SessionConstant;
import com.edou.member.entity.MemberLoginToken;
import com.edou.member.entity.MemberUser;
import com.edou.member.service.IMemberLoginTokenService;
import com.edou.member.service.IMemberUserService;

/**
 * 会员APP端登录拦截器
 * @creator     admin
 * @create-time Jun 19, 2015   2:09:07 PM
 * @version 1.0
 */
public class MemberAppLoginInterceptor extends HandlerInterceptorAdapter {
	
	@Resource(name = "memberLoginTokenServiceImpl")
	private IMemberLoginTokenService memberLoginTokenService;
	@Resource(name = "memberUserServiceImpl")
	private IMemberUserService memberUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		//判断token
		String loginToken = (String) request.getParameter("loginToken");
		if(StringUtils.isNotBlank(loginToken)){
			//验证
			Date now = new Date();
			MemberLoginToken memberLoginToken = memberLoginTokenService.getMemberLoginTokenByToken(loginToken);
			if(null != memberLoginToken){
				if(now.before(memberLoginToken.getExpireTime())){
					//存在并且没有过期
					
					//设置过期时间
					Calendar cal = Calendar.getInstance(Locale.CHINA);
					cal.setTime(now);
					cal.add(Calendar.DAY_OF_YEAR, 30);	//增加1个月
					Date expireTime = cal.getTime();
					memberLoginToken.setExpireTime(expireTime);
					memberLoginTokenService.updateExpireTime(memberLoginToken);
					
					//查询会员
					MemberUser member = memberUserService.getMemberUserById(memberLoginToken.getMemberId());
					request.setAttribute(SessionConstant.CURRENT_MEMBER, member);
					
					//验证通过
					return super.preHandle(request, response, handler);
				}
				
				//已经过期，删除 0628测试阶段暂时注释
				//memberLoginTokenService.delByIds(new Long[]{memberLoginToken.getId()});
			}
		}
		
		//验证失败，提示需要登录
		response.setContentType("text/json;charset=UTF-8");
		response.getWriter().write("{\"status\":\"needLogin\",\"message\":\"登录超时，请重新登录\"}");
		
		return false;
	}
	
}
